<template>
	<view class="navigation">
		<eui-navbar ref="EuiNavBar" title="仓库选择" displayable="true" color="#000000" backgroundColor="#FFFFFF" />
		<view class="top-view">
			<eui-search-bar v-model="searchValue" @confirm="selStoreById" radius="100" placeholder="请输入编码" />
		</view>
		<view class="footer-view" :style="{ height: listHeight + 'rpx' }">
			<scroll-view scroll-y lower-threshold='88' :refresher-triggered="triggered" @refresherrefresh="onRefresh"
				:refresher-enabled='true' class="scroll-area" :style="{width:scrollWidth,height:scrollHeight}">
				<view class="padding-left-28 font-size-28 flex flex-direction-column" v-for="(item,index) in dateList"
					:key="index" @click="setSelBackItem(item)">
					<view class="sroll-store-list flex">
						<view class="flex align-items-center margin-right-10">
							<checkbox value="cb" :checked="item.c_checked" @click.stop="setSelBackItem(item)"
								:color="themeColor" :class="[theme]" style="transform:scale(0.8)" v-if="IsMult=='是'"/>
							<radio :value="item.c_wno" :checked="item.c_checked" @click.stop="setSelBackItem(item)"
								:color="themeColor" :class="[theme]" style="transform:scale(0.8)" v-else/>
						</view>
						<view>
							<eui-text type="titlename2" title="仓库:" :value="item.c_wno" :name="item.c_name"
								cWidth="width: 100%" />
							<eui-text type="name2" title="机构:" :value="getName('rdsStores',item.c_store_id)"
								cWidth="width: 100%" />
							<eui-text type="name2" title="是否独立核算:" :value="getDictName('是非',item.c_is_cost)"
								cWidth="width: 100%" />
							<eui-text type="name2" title="核算仓库:" :value="getName('rdsWnos',item.c_wno_wb)"
								cWidth="width: 100%" />
						</view>
					</view>
				</view>
			</scroll-view>
			<view class="user-footer flex-1 flex">
				<!-- <eui-button type="primary" title="确定" @click="BackMultParm" singleTag="primary_主按钮" /> -->
				<view class="flex-1 flex" style="padding-right: 7.5px;" @click="CancelCondition">
					<view class="flex-1 flex justify-content-center align-items-center bottom-bg"
						style="border: solid 1px rgba(136, 136, 136, 1);font-size: 15px;">取消</view>
				</view>
				<view class="flex-1 flex justify-content-center align-items-center" style="padding-left: 7.5px;"
					@click="BackMultParm">
					<view class="flex-1 flex justify-content-center align-items-center bottom-bg button-theme"
						:class="{'opacity-half':!hasChecked,[theme]:true}" style="color: #fff;font-size: 15px;">
						确认</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup type="ts">
	import {ref, onMounted, reactive} from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import service from '../../common/service';
import Enjoy from '../../common/enjoy';
import { useMainStore } from "@/store/modules/store";
import { useLoginStore } from "@/store/modules/useLoginStore";
import { rdsRequest, getRdsUrl } from '@/hooks/rdsServices';
import { useThemeStore } from '@/store/themeStore';
import { storeToRefs } from 'pinia';
const themeStore = useThemeStore(); // 主题
const { theme } = storeToRefs(themeStore);
const themeColor = ref(themeStore.theme == 'theme-blue' ? '#02B7E6' : '#FF6430')
const rdsUrl = getRdsUrl();
const mainStore = useMainStore();
const LoginStore = useLoginStore();
const listHeight = ref(300);
const scrollWidth = ref(uni.getSystemInfoSync().windowWidth - 20 + 'px');
const scrollHeight = ref(uni.getSystemInfoSync().windowHeight -uni.getSystemInfoSync().statusBarHeight-uni.getSystemInfoSync().safeAreaInsets.bottom - 150 +'px');
const hasChecked = ref(false)
const searchValue = ref('');
const dataPage = ref({
  CurrentPage: 1, //当前页码
  PageCount: 0,//总共多少页
  PageSize:20,//一页多少条
  RowsCount: 0,//总共多少条
});
const IsMult = ref('否');
const SelectedItems = ref("");
const c_store_id = ref("");
const triggered = ref(false);
const WhereList = ref([]);
const dateList = ref([]);

let rdsDict = reactive([]);
let dictMap = reactive({});
let rdsStoresMap = reactive({}); //机构
let rdsWnosMap = reactive({}); //仓库

onMounted (async () => {
  await getAllDicData();
  await getListHeight();
})

// 获取列表高度
const getListHeight = async () => {
  await uni.getSystemInfo({
    success: function (res) { // res - 各种参数
      let info = uni.createSelectorQuery().select(".footer-view");
      info.boundingClientRect(function (data) { //data - 各种参数
        //获取列表高度
        let height = res.windowHeight - data.top;
        //转换rpx
        listHeight.value = height / (res.windowWidth / 750) - 100;
      }).exec()
    }
  });
};

const getAllDicData = async () => {
  rdsDict = await service.getLocalStorage('rdsDict');
  dictMap = new Map();
  for (const item of rdsDict) {
    const key = item.c_class_name;
    const value = item.c_id;
    const name = item.c_name;
    if (!dictMap.has(key)) {
      dictMap.set(key, new Map());
    }
    dictMap.get(key).set(value, name);
  }
  rdsStoresMap = await service.getLocalStorage('rdsStores');
  rdsWnosMap = await service.getLocalStorage('rdsWnos');
}

const selStoreById =()=>{
  dataPage.value.CurrentPage = 1;
  dateList.value = [];
  getData();
}
const setSelBackItem = e=>{
  if(IsMult.value == '否'){
	  for (let i = 0; i < dateList.value.length; i++) {
	  	dateList.value[i].c_checked=false;
	  	if(dateList.value[i].c_wno == e.c_wno){
	  		dateList.value[i].c_checked=true;
	  	}
	  }
    // let parms = {
    //   Key: e.c_wno,
    //   Value: e.c_name,
    // }
    // Enjoy.DialogCallBack(parms)
  }else{
    e.c_checked = !e.c_checked;
  }
  DataHasChecked()
}
// 多选情况下处理选中的数据以及返回处理
const BackMultParm = () =>{
	if(!hasChecked.value){
		return false
	}
  let cKey = [];
  let cValue = [];
  for (let i = 0; i < dateList.value.length; i++) {
    if(dateList.value[i].c_checked){
      cKey.push(dateList.value[i].c_wno);
      cValue.push(dateList.value[i].c_name);
    }
  }
  if(cKey.length==0){
    uni.showToast({
      duration: 3500,
      icon: 'none',
      title: '请先选择部门!',
    });
    return false;
  }
  let parms = {
    Key: cKey.toString(),
    Value: cValue.toString(),
  }
  Enjoy.DialogCallBack(parms)
}
// 下拉刷新
const onRefresh = () =>{
  if (triggered.value) {
    return false;
  }
  triggered.value = true;
  dataPage.value.CurrentPage = 1;
  dateList.value = [];
  getData();
  setTimeout(() => {
    triggered.value = false;
  }, 1000)
}
// 加载更多
const templateLower = () =>{
  if (dataPage.value.CurrentPage < dataPage.value.PageCount) {
    dataPage.value.CurrentPage +=1;
    getData();
  }
}
const getData = async () =>{
  service.enjoyShowLoading('正在加载...');
  const req = {
    WhereList:[
      { c_col: "c_store_id", c_oper: "等于", c_value: c_store_id.value, c_logic: "而且", },
    ]
  };
  if (searchValue.value) {
    req.WhereList.push({
      c_col: "c_wno",
      c_oper: "等于",
      c_value: searchValue.value,
      c_logic: "而且",
    });
  }
  const result = await rdsRequest(rdsUrl.bcApi, '弹窗通用查询', 'FetchWno',req);
  service.enjoyHideLoading();
  if (result.ReturnObject.length > 0){
    dateList.value = result.ReturnObject;
	DataHasChecked()
  }else {
    uni.showToast({
      duration: 3500,
      icon: 'none',
      title: '未查询到数据',
      mask: true,
    });
  }
}


const getName = (key, value) => {
  let list = [];
  if (!value) {
    return ''
  }
  value.split(',').map(item => {
    const flag = isEnglishLettersOnly(key)
    if (flag) {
      list.push("[" + item + "]" + getRelatedName(key, item) || '');
    } else {
      list.push("[" + item + "]" + key);
    }
  })
  return list.join(',');
}

const isEnglishLettersOnly = (str) => {
  // 正则表达式，匹配所有的英文字母
  const regex = /^[A-Za-z]+$/;
  return regex.test(str);
}

const getRelatedName = (key, value) => {
  switch (key) {
    case 'rdsStores':
      return rdsStoresMap[value] ? rdsStoresMap[value] : '';
    case 'rdsWnos':
      return rdsWnosMap[value] ? rdsWnosMap[value] : '';
    default:
      return ''
  }
}

const getDictName = (key, value) => {
  const dictMap = rdsDict.find(x => x.c_class_name === key && x.c_id === value);
  return dictMap ? dictMap.c_name : ''
}
const CancelCondition = () =>{
	uni.navigateBack({
		delta: 1
	});
}
const DataHasChecked = () =>{
	hasChecked.value = false;
	for (let i = 0; i < dateList.value.length; i++) {
		if(dateList.value[i].c_checked){
			hasChecked.value = true;
		}
	}
}
onLoad(option=>{
  let { SelectionStoreId } = option;
  c_store_id.value = SelectionStoreId;
	if(option&&option.IsMult){
		IsMult.value = option.IsMult;
	}
	if(option&&option.SelectedItems){
		SelectedItems.value = option.SelectedItems;
	}
  getData();
})
</script>

<style lang="scss" scoped>
	@import '../../main.scss';

	.flex {
		display: flex;
	}

	.flex-1 {
		flex: 1;
	}

	.flex-direction-column {
		flex-direction: column !important;
	}

	.margin-top-20 {
		margin-top: 20rpx;
	}

	.font-size-24 {
		font-size: 24rpx;
	}

	.padding-left-28 {
		padding-left: 28rpx;
	}

	.content-img {
		background-color: #FFFFFF;
		background-repeat: no-repeat;
		width: 100%;
	}

	.color-888 {
		color: rgba(136, 136, 136, 1);
	}

	.main-view {
		flex: 1;
		flex-direction: column;
		padding: 20rpx;
		background-color: #f2f2f2;
	}

	.main-view-bg {
		border-radius: 20rpx;
		padding: 20rpx 0;
	}

	.sroll-store-list {
		padding: 20rpx 28rpx 20rpx 0;
		border-bottom: solid 1px rgba(238, 238, 238, 1);
		line-height: 1;
	}

	.font-size-28 {
		font-size: 28rpx;
	}

	.store-checked {
		background-color: rgba(249, 250, 252, 1) !important;
	}

	.user-footer {
		position: fixed;
		z-index: 9;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 10rpx 28rpx;
	}

	.navigation {
		display: flex;
		height: 100vh;
		width: 100%;
		flex-direction: column;
		background: #F2F2F2;
	}

	.top-view {
		width: 100%;
		height: 88rpx;
		background: #FFFFFF;
		margin-bottom: 20rpx;
	}

	.footer-view {
		width: 100%;
		flex: 1;
	}

	.scroll-area {
		width: calc(100% - 40rpx);
		height: calc(100% - 20rpx);
		margin: 0 20rpx 20rpx 20rpx;
		background-color: #fff;
		border-radius: 20rpx;
	}

	.justify-content-center {
		justify-content: center;
	}

	.bottom-bg {
		height: 40px;
		border-radius: 20px;
	}

	.align-items-center {
		align-items: center;
	}

	.button-theme {
		background: var(--theme-bgc-color);
	}

	.font-weight-bold {
		font-weight: 600;
	}

	::v-deep .uni-checkbox-input {
		border-radius: 50%;
		// background: var(--theme-bgc-color);
		border: 1px solid var(--theme-color);
	}

	::v-deep .uni-checkbox-input svg {
		transform: translate(-100%, -100%) scale(1);
		background: var(--theme-bgc-color);
		border-radius: 50%;
		color: #fff !important;
		top: 22px;
		left: 22px;
	}

	::v-deep .uni-checkbox-input svg path {
		fill: #fff !important;
		transform: translate(10%, 10%) scale(0.8);
	}

	.opacity-half {
		opacity: 0.5;
	}
</style>